package com.zx.znav.handler;

import com.zx.znav.error.BusinessException;
import com.zx.znav.error.EnumBusinessError;
import com.zx.znav.response.CommonReturnType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec 全局异常处理
 * 处理未被controller层吸收的exception
 * @since 2023 - 07 - 19 - 14:01
 */
@ControllerAdvice
public class ControllerExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    //业务异常返回Json数据
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(HttpServletRequest request, Exception e) {
        logger.error("Request URL:{}, Exception:{}", request.getRequestURL(), e);
        Map<String, Object> responseData = new HashMap<>();
        BusinessException businessException = (BusinessException) e;
        responseData.put("errorCode", businessException.getErrorCode());
        responseData.put("errorMessage", businessException.getErrorMessage());
        return CommonReturnType.create(responseData, CommonReturnType.FAIL);
    }

    //非业务异常返回error页面
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ModelAndView handlerException2(HttpServletRequest request, Exception e) {
        logger.error("Request URL:{}, Exception:{}", request.getRequestURL(), e);
        ModelAndView modelAndView = new ModelAndView("error/error");
        modelAndView.addObject("exception");
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("errorCode", EnumBusinessError.UNKNOWN_ERROR.getErrorCode());
        responseData.put("errorMessage", EnumBusinessError.UNKNOWN_ERROR.getErrorMessage());
        modelAndView.addObject("msg", responseData);
        return modelAndView;
    }
}
